package com.ikproducts.manualian.server;


import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import com.ikproducts.manualian.client.ContentData;
import com.ikproducts.manualian.client.ContentType;
import com.ikproducts.manualian.client.GreetingService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
    GreetingService {

	public Map<String,String> greetServer(String input) {
		Map<String,String> map = new HashMap<String,String>();
		UserService service = UserServiceFactory.getUserService();
		StringBuilder strHtml = new StringBuilder();
		if(service.isUserLoggedIn()){
			String logoutUrl = service.createLogoutURL("");
			User user = service.getCurrentUser();
			String email = user.getEmail();
			map.put("isLoggedIn", "true");
			map.put("emailAddress", email);
			map.put("logoutUrl", logoutUrl);
		}
		else
		{
			map.put("isLoggedIn", "false");
		}
		return map;
	}
	
	public String saveArticle(List<ContentData> data, String userName, String title, String categoryPathOfDisplayName, String categoryPathOfIDName, int categoryID){
		String retStr = "成功";
		List<Content> contents = new ArrayList<Content>();
		for(ContentData d : data){
			Content content = new Content(d.ContentType, new Text(d.Content));
			contents.add(content);
		}
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Article article = new Article(userName, title, contents, categoryPathOfDisplayName, categoryPathOfIDName, categoryID);
		
		try{
			pm.makePersistent(article);
		}
		catch(Exception e){
			retStr = "失敗";
		}
		finally{
			pm.close();
		}
		return retStr;
	}
	
	public String saveSeri(List<ContentData> data, String userName, String title, String categoryPathOfDisplayName, String categoryPathOfIDName, int categoryID){
		String retStr = "成功";
		List<Content> contents = new ArrayList<Content>();
		for(ContentData d : data){
			Content content = new Content(d.ContentType, new Text(d.Content));
			contents.add(content);
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Article article = new Article(userName, title, contents, categoryPathOfDisplayName, categoryPathOfIDName, categoryID);
		
 
/*		try{
			pm.makePersistent(s);
		}
		catch(Exception e){
			retStr = "失敗";
		}
		finally{
			pm.close();
		}
*/		
		return retStr;
	}
	
	public String getCategoryXMLData(String url){
		String result = "";
		URLFetchService ufs = URLFetchServiceFactory.getURLFetchService();
		try{
			HTTPRequest httpRequest = new HTTPRequest(new URL(url));
			HTTPResponse httpResponse = ufs.fetch(httpRequest);
			if(httpResponse.getResponseCode() == 200){
				result = new String(httpResponse.getContent());	
			}
		}
		catch(Exception e){
			result = e.getStackTrace() + " + " + e.getMessage();
		}
		return result;
	}

	public String GetTemp(){
		StringBuilder sb = new StringBuilder();

		PersistenceManager pm = PMF.get().getPersistenceManager();
/*		Category c = new Category("pappa");
		try
		{
			pm.makePersistent(c);
		}
		finally{
			pm.close();
		}
*/
		try{
			Transaction txn = pm.currentTransaction();
			txn.begin();
			
			Query query = pm.newQuery(Article.class);
			try{
				List<Article> cats = (List<Article>)query.execute();
				
				for(int i=0; i<3;i++){
					pm.deletePersistent(cats.get(i));
				}
				txn.commit();
/*				for(Article a : cats){
					sb.append(a.get_UserName());
				}
*/			}
			catch(Exception ex){
				sb.append("1: " + ex.getStackTrace());
			}
			finally{
				if(txn.isActive())txn.rollback();
				query.closeAll();
			}
		}
		catch(Exception e){
			sb.append("2: " + e.getStackTrace());
		}
		finally{
			pm.close();
		}

		return sb.toString();
	}

}
